package com.zifan.sever.controller;

import com.zifan.sever.bean.Admin;
import com.zifan.sever.service.IAdminService;
import com.zifan.sever.utils.RespBean;
import com.zifan.sever.vo.AdminLoginParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 用户登录
 * @author Zifan
 * @date 2021年04月10日16:55
 */
@RestController
@Api(tags = "LoginController")
public class LoginController {

    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        return adminService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword(),adminLoginParam.getCode(),request);
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        return RespBean.success("注销成功");
    }

    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal){
        if (principal == null){
            //登录有问题
            return null;
        }
        String username = principal.getName();
        //根据用户名获取完整的用户对象
        Admin admin = adminService.getAdminByUsername(username);
        admin.setPassword(null);
        //查询的时候将该用户的角色信息给设置上
        admin.setRoles(adminService.getRolesByAdminId(admin.getId()));
        return admin;
    }
}
